package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.common.cache.GmallCache;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.model.product.*;
import com.atguigu.gmall.product.mapper.*;
import com.atguigu.gmall.product.service.ManageService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ManageServiceImpl implements ManageService {

    @Resource
    private BaseCategory1Mapper baseCategory1Mapper;

    @Resource
    private BaseCategory2Mapper baseCategory2Mapper;

    @Resource
    private BaseCategory3Mapper baseCategory3Mapper;

    @Resource
    private BaseAttrInfoMapper baseAttrInfoMapper;

    @Resource
    private BaseAttrValueMapper baseAttrValueMapper;

    @Resource
    private BaseTrademarkMapper baseTrademarkMapper;

    @Resource
    private SpuInfoMapper spuInfoMapper;

    @Resource
    private BaseSaleAttrMapper baseSaleAttrMapper;

    @Resource
    private SpuSaleAttrMapper spuSaleAttrMapper;

    @Resource
    private SpuSaleAttrValueMapper spuSaleAttrValueMapper;

    @Resource
    private SpuImageMapper spuImageMapper;

    @Resource
    private SkuInfoMapper skuInfoMapper;

    @Resource
    private SkuAttrValueMapper skuAttrValueMapper;

    @Resource
    private SkuSaleAttrValueMapper skuSaleAttrValueMapper;

    @Resource
    private SkuImageMapper skuImageMapper;

    @Resource
    private BaseCategoryViewMapper baseCategoryViewMapper;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private RedissonClient redissonClient;

    @Resource
    private RabbitService rabbitService;

    //获取一级分类数据
    @Override
    public List<BaseCategory1> getCategory1() {
        return baseCategory1Mapper.selectList(null);
    }

    //获取二级分类数据
    @Override
    public List<BaseCategory2> getCategory2(Long category1Id) {
        return baseCategory2Mapper.selectList(new QueryWrapper<BaseCategory2>()
                .eq("category1_id",category1Id));
    }

    //获取三级分类数据
    @Override
    public List<BaseCategory3> getCategory3(Long category2Id) {
        return baseCategory3Mapper.selectList(new QueryWrapper<BaseCategory3>()
                .eq("category2_id",category2Id));
    }

    //根据分类id获取平台属性
    @Override
    public List<BaseAttrInfo> attrInfoList(Long category1Id, Long category2Id, Long category3Id) {

        return baseAttrInfoMapper.attrInfoList(category1Id,category2Id,category3Id);
    }

    //添加平台属性
    @Override
    public void saveAttrInfo(BaseAttrInfo baseAttrInfo) {
        baseAttrInfoMapper.insert(baseAttrInfo);
        List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList();
        if(attrValueList != null && attrValueList.size() > 0){
            attrValueList.forEach(attrValue -> {
                //外键
                attrValue.setAttrId(baseAttrInfo.getId());
                baseAttrValueMapper.insert(attrValue);
            });
        }
    }

    //修改平台属性
    @Override
    public void updateAttrInfo(BaseAttrInfo baseAttrInfo) {
        baseAttrInfoMapper.updateById(baseAttrInfo);
        List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList();
        if(attrValueList != null && attrValueList.size() > 0){
            attrValueList.forEach(attrValue -> {
                //外键
                if (attrValue.getId() != null){
                    baseAttrValueMapper.updateById(attrValue);
                } else {
                    attrValue.setAttrId(baseAttrInfo.getId());
                    baseAttrValueMapper.insert(attrValue);
                }
            });
        }
    }

    //获取品牌属性列表
    @Override
    public List<BaseTrademark> getTrademarkList() {
        List<BaseTrademark> baseTrademarkList = baseTrademarkMapper.selectList(null);
        return baseTrademarkList;
    }

    //品牌列表添加
    @Override
    public void baseTrademarkSave(BaseTrademark baseTrademark) {
        baseTrademarkMapper.insert(baseTrademark);
    }

    //品牌列表删除
    @Override
    public void baseTrademarkRemove(Long id) {
        baseTrademarkMapper.delete(new QueryWrapper<BaseTrademark>().eq("id",id));
    }

    //查询品牌列表某个属性
    @Override
    public BaseTrademark baseTrademarkGet(Long id) {
        BaseTrademark baseTrademark = baseTrademarkMapper.selectById(id);
        return baseTrademark;
    }

    //修改品牌列表某个属性
    @Override
    public void baseTrademarkUpdate(BaseTrademark baseTrademark) {
        baseTrademarkMapper.updateById(baseTrademark);
    }

    //获取销售属性
    @Override
    public List<BaseSaleAttr> baseSaleAttrList() {
        return baseSaleAttrMapper.selectList(null);
    }

    //添加spu
    @Override
    public void saveSpuInfo(SpuInfo spuInfo) {
        spuInfoMapper.insert(spuInfo);
        List<SpuSaleAttr> spuSaleAttrList = spuInfo.getSpuSaleAttrList();
        List<SpuImage> spuImageList = spuInfo.getSpuImageList();
        if (spuSaleAttrList != null && spuSaleAttrList.size() > 0){
            for (SpuSaleAttr spuSaleAttr : spuSaleAttrList) {
                spuSaleAttr.setSpuId(spuInfo.getId());
                spuSaleAttrMapper.insert(spuSaleAttr);
                List<SpuSaleAttrValue> spuSaleAttrValueList = spuSaleAttr.getSpuSaleAttrValueList();
                if (spuSaleAttrValueList != null && spuSaleAttrValueList.size() > 0){
                    for (SpuSaleAttrValue spuSaleAttrValue : spuSaleAttrValueList) {
                        spuSaleAttrValue.setSpuId(spuInfo.getId());
                        spuSaleAttrValue.setSaleAttrName(spuSaleAttr.getSaleAttrName());
                        spuSaleAttrValueMapper.insert(spuSaleAttrValue);
                    }
                }
            }
        }
        if (spuImageList != null && spuImageList.size() > 0){
            for (SpuImage spuImage : spuImageList) {
                spuImage.setSpuId(spuInfo.getId());
                spuImageMapper.insert(spuImage);
            }
        }

    }

    //根据spuId获取图片列表
    @Override
    public List<SpuImage> spuImageList(Long spuId) {
        List<SpuImage> spuImageList = spuImageMapper.selectList(new QueryWrapper<SpuImage>()
                .eq("spu_id", spuId));
        return spuImageList;
    }

    //根据spuId获取销售属性及属性值
    @Override
    public List<SpuSaleAttr> spuSaleAttrList(Long spuId) {
        List<SpuSaleAttr> spuSaleAttrList = spuSaleAttrMapper.spuSaleAttrList(spuId);
        return spuSaleAttrList;
    }

    //添加sku
    @Override
    public void saveSkuInfo(SkuInfo skuInfo) {
        skuInfo.setIsSale(SkuInfo.NOSALE);
        skuInfoMapper.insert(skuInfo);
        List<SkuAttrValue> skuAttrValueList = skuInfo.getSkuAttrValueList();
        List<SkuSaleAttrValue> skuSaleAttrValueList = skuInfo.getSkuSaleAttrValueList();
        List<SkuImage> skuImageList = skuInfo.getSkuImageList();
        if (skuAttrValueList != null && skuAttrValueList.size() > 0){
            for (SkuAttrValue skuAttrValue : skuAttrValueList) {
                skuAttrValue.setSkuId(skuInfo.getId());
                skuAttrValueMapper.insert(skuAttrValue);
            }
        }
        if (skuSaleAttrValueList != null && skuSaleAttrValueList.size() > 0){
            for (SkuSaleAttrValue skuSaleAttrValue : skuSaleAttrValueList) {
                skuSaleAttrValue.setSkuId(skuInfo.getId());
                skuSaleAttrValue.setSpuId(skuInfo.getSpuId());
                skuSaleAttrValueMapper.insert(skuSaleAttrValue);
            }
        }
        if (skuImageList != null && skuImageList.size() > 0){
            for (SkuImage skuImage : skuImageList) {
                skuImage.setSkuId(skuInfo.getId());
                skuImageMapper.insert(skuImage);
            }
        }
    }

    //获取sku分页列表
    @Override
    public IPage skuList(Integer page, Integer limit) {
        IPage<SkuInfo> iPage = skuInfoMapper.selectPage(new Page<>(page, limit), null);
        return iPage;
    }

    //上架
    @Override
    public void onSale(Long skuId) {
        SkuInfo skuInfo = skuInfoMapper.selectById(skuId);
        skuInfo.setIsSale(SkuInfo.ISSALE);
        skuInfoMapper.updateById(skuInfo);
        //MQ发送消息 将来保存到ES中
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_GOODS,MqConst.ROUTING_GOODS_UPPER,skuId);
    }

    //下架
    @Override
    public void cancelSale(Long skuId) {
        SkuInfo skuInfo = skuInfoMapper.selectById(skuId);
        skuInfo.setIsSale(SkuInfo.NOSALE);
        skuInfoMapper.updateById(skuInfo);
        //MQ发送消息 将来删除ES中的数据
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_GOODS,MqConst.ROUTING_GOODS_LOWER,skuId);
    }

    //查询一级、二级、三级分类信息
    @Override
    @GmallCache(prefix = "getBaseCategoryView")
    public BaseCategoryView getBaseCategoryView(Long category3Id) {

        BaseCategoryView baseCategoryView = baseCategoryViewMapper.selectById(category3Id);
        return baseCategoryView;
    }

    //查询skuinfo基本信息及图片信息
    @Override
    @GmallCache(prefix = "getSkuInfo")
    public SkuInfo getSkuInfo(Long skuId) {
        return skuInfoMapper.getSkuInfo(skuId);
    }
    /*@Override
    public SkuInfo getSkuInfo(Long skuId) {
        String cacheKey = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKUKEY_SUFFIX;
        SkuInfo skuInfo = (SkuInfo) redisTemplate.opsForValue().get(cacheKey);
        if (skuInfo != null){
            return skuInfo;
        } else {
            //解决缓存击穿
            String lockKey = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKULOCK_SUFFIX;
            RLock lock = redissonClient.getLock(lockKey);
            try {
                Boolean isTryLock = lock.tryLock(1, 2, TimeUnit.SECONDS);
                if (isTryLock){
                    skuInfo = skuInfoMapper.getSkuInfo(skuId);
                    //解决缓存穿透
                    if (skuInfo != null){
                        //解决缓存雪崩
                        redisTemplate.opsForValue().set(cacheKey,skuInfo,
                                RedisConst.SKUKEY_TIMEOUT + new Random().nextInt(300), TimeUnit.SECONDS);
                    } else {
                        skuInfo = new SkuInfo();
                        redisTemplate.opsForValue().set(cacheKey,skuInfo,5, TimeUnit.MINUTES);
                    }
                    lock.unlock();
                } else {
                    TimeUnit.SECONDS.sleep(2);
                    skuInfo = (SkuInfo) redisTemplate.opsForValue().get(cacheKey);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return skuInfo;
    }*/

    //查询skuinfo基本信息及图片信息
    /*@Override
    public SkuInfo getSkuInfo(Long skuId) {
        //查询redis缓存 如果存在数据直接返回，不存在则添加缓存并返回
        String cacheKey = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKUKEY_SUFFIX;
        SkuInfo skuInfo = (SkuInfo) redisTemplate.opsForValue().get(cacheKey);
        if (skuInfo != null){
            return skuInfo;
        } else {
            //解决缓存击穿 上分布式锁
            String uuid = UUID.randomUUID().toString();
            String lockKey = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKULOCK_SUFFIX;
            Boolean isLock = redisTemplate.opsForValue().setIfAbsent(lockKey, uuid,5, TimeUnit.SECONDS);
            if (isLock){
                skuInfo = skuInfoMapper.getSkuInfo(skuId);
                //解决缓存穿透
                if (skuInfo != null){
                    //解决缓存雪崩
                    redisTemplate.opsForValue().set("cacheKey",skuInfo,
                            RedisConst.SKUKEY_TIMEOUT + new Random().nextInt(300), TimeUnit.SECONDS);
                } else {
                    skuInfo = new SkuInfo();
                    redisTemplate.opsForValue().set("cacheKey",skuInfo,5,TimeUnit.MINUTES);
                }
                //防止锁被误删
                //String u = (String) redisTemplate.opsForValue().get(lockKey);
                //if (uuid.equals(u)){
                //   redisTemplate.delete(lockKey);
                //}
                //释放锁
                String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return tostring(redis.call('del',KEYS[1])) else return 0 end";
                this.redisTemplate.execute(new DefaultRedisScript<>(script), Collections.singletonList(lockKey), uuid);
            } else {
                //防止查缓存前 缓存中还没有存入数据
                try {
                    TimeUnit.SECONDS.sleep(2);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                skuInfo = (SkuInfo) redisTemplate.opsForValue().get(cacheKey);
            }
        }
        return skuInfo;
    }*/

    //查询Sku价格信息
    @Override
    public BigDecimal getPrice(Long skuId) {
        return skuInfoMapper.getPrice(skuId);
    }

    //查询Sku总销售属性及属性值 同时默认选中一个商品
    @Override
    @GmallCache(prefix = "getSpuSaleAttrListCheckBySku")
    public List<SpuSaleAttr> getSpuSaleAttrListCheckBySku(Long skuId, Long spuId) {
        return spuSaleAttrMapper.getSpuSaleAttrListCheckBySku(skuId,spuId);
    }

    //查询页面上组合与skuId的关系
    @Override
    @GmallCache(prefix = "getSkuValueIdsMap")
    public Map<String, String> getSkuValueIdsMap(Long spuId) {
        List<Map<String, Object>> mapList = skuSaleAttrValueMapper.getSkuValueIdsMap(spuId);
        //mapList.stream().forEach(System.out::println);
        Map<String, String> hashMap = new HashMap<>();
        if (mapList != null && mapList.size() > 0){
            for (Map<String, Object> map : mapList) {
                hashMap.put(String.valueOf(map.get("value_ids")),String.valueOf(map.get("sku_id")));
            }
        }
        return hashMap;
    }

    //查询所有的一级、二级、三级分类信息
    @Override
    public List<BaseCategoryView> getBaseCategoryViewList() {
        return baseCategoryViewMapper.selectList(null);
    }

    //根据品牌ID查询一个品牌信息
    @Override
    public BaseTrademark getBaseTrademark(Long tmId) {
        return baseTrademarkMapper.selectById(tmId);
    }

    //根据skuId查询 SkuAttrValue
    @Override
    public List<SkuAttrValue> getSkuAttrValue(Long skuId) {
        return skuAttrValueMapper.getSkuAttrValue(skuId);
    }

    //根据平台属性ID获取平台属性
    @Override
    public List<BaseAttrValue> getAttrValueList(Long attrId) {
        List<BaseAttrValue> baseAttrValueList = baseAttrValueMapper.selectList(new QueryWrapper<BaseAttrValue>()
                .eq("attr_id", attrId));
        return baseAttrValueList;
    }

    //获取品牌分页列表
    @Override
    public IPage baseTrademark(Integer page, Integer limit) {
        IPage<BaseTrademark> baseTrademarkIPage = baseTrademarkMapper.selectPage(new Page<>(page, limit), null);
        return baseTrademarkIPage;
    }

    //获取spu分页列表
    @Override
    public IPage findSpuList(Integer page, Integer limit, Long category3Id) {
        IPage<SpuInfo> spuInfoIPage = spuInfoMapper.selectPage(new Page<>(page, limit),
                new QueryWrapper<SpuInfo>().eq("category3_id",category3Id));
        return spuInfoIPage;
    }

}
